﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using SelectLib;

namespace Queue_Test
{
    class Program
    {
        static TMsgQueue<CMsg> intMsg = new TMsgQueue<CMsg>();
        static bool th1Flag = false;
        static bool th2Flag = false;

        static void Main(string[] args)
        {
            /*Queue<int> ique = new Queue<int>();
            for (int i = 1; i <= 10; i++) ique.Enqueue(i);
            Console.WriteLine(ique.Count);

            int count = ique.Count;
            for(int i=0;i<count;i++)
            {
                Console.WriteLine("取出：" + ique.Dequeue().ToString() + "，余下数量：" + ique.Count.ToString());
            }*/

            Thread th1 = new Thread(Th1);
            th1.IsBackground = true;
            th1.Start();

            Thread th2 = new Thread(Th2);
            th2.IsBackground = true;
            th2.Start();

            Thread th3 = new Thread(Th3Out);
            th3.IsBackground = true;
            th3.Start();

            Thread.Sleep(100);
            while (th1Flag==false || th2Flag==false);
            //while (th1Flag==false) ;
            Thread.Sleep(200);
            Console.WriteLine("Count ={0}", intMsg.msgQueue.Count);

            Console.ReadKey();
        }

        static void Th1()
        {
            for(int i=0;i< 1000000; i++)
            {
                if(i%10000 == 0)Console.WriteLine("Th1 = " + i.ToString());
                intMsg.InQueue(new CMsg() {
                    id=i+1,
                    Msg="is " + (i+1).ToString()
                });
            }
            th1Flag = true;
            Console.WriteLine("Th1 OK! ");
        }

        static void Th2()
        {
            for (int i = 1000000; i < 2000000; i++)
            {
                if (i % 10000 == 0) Console.WriteLine("Th2 = " + i.ToString());
                intMsg.InQueue(new CMsg()
                {
                    id = i + 1,
                    Msg = "is " + (i + 1).ToString()
                });
            }
            th2Flag = true;
            Console.WriteLine("Th2 OK! ");
        }

        static void Th3Out()
        {
            int readCount = 0;
            while(true)
            {
                Thread.Sleep(50);
                int count = intMsg.msgQueue.Count;
                if (count == 0) break;
                for(int i = 0; i < count; i++)
                {
                    readCount++;
                    intMsg.OutQueue();
                }
            }
            Console.WriteLine("Th3Out readCount={0}", readCount);
        }

        static void Th4Out()
        {

        }

    }
}
